package com.bawei.es.service.impl;

import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.es.service.EsIndexService;
import com.bawei.system.domain.vo.EsDocDelVo;
import com.bawei.system.domain.vo.EsIndexVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EsIndexServiceImpl implements EsIndexService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public R<Boolean> indexCreate(String indexName) {
        //如果索引为空 抛出异常
        if (StringUtils.isEmpty(indexName)) {
            throw new ServiceException("索引名称不能为空");
        }
        CreateIndexRequest request = new CreateIndexRequest(indexName);



        try {
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            if (createIndexResponse.isAcknowledged()) {
                return R.ok(true);
            }
        } catch (IOException e) {
            log.error("连接ES服务异常:{}", e);
            throw new RuntimeException("创建索引失败，请联系管理员或查看服务日志");
        }
        return R.fail(false, "索引创建失败");
    }

    @Override
    public R<Boolean> indexExit(String indexName) {
        if (StringUtils.isEmpty(indexName)) {
            throw new ServiceException("indexName不能为空");
        }
        GetIndexRequest indexRequest = new GetIndexRequest(indexName);
        try {
            boolean exists = restHighLevelClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
            return R.ok(exists);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.fail(false, "查询失败！");
    }

    @Override
    public R<Boolean> indexCreateWithMapping(EsIndexVo esIndexVo) {
        String indexName = esIndexVo.getIndexName();
        Map<String, Object> indexSettings = esIndexVo.getIndexSettings();
        Map<String, Object> indexMappings = esIndexVo.getIndexMappings();
        if (StringUtils.isEmpty(indexName) || StringUtils.isEmpty(indexMappings) || StringUtils.isEmpty(indexSettings)) {
            throw new ServiceException("indexName、indexMapping不能为空");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String indexMappingsJson = objectMapper.writeValueAsString(esIndexVo.getIndexMappings());
            String indexSettingsJson = objectMapper.writeValueAsString(esIndexVo.getIndexSettings());

            CreateIndexRequest request =  new CreateIndexRequest(indexName);
            request.source(indexMappingsJson, XContentType.JSON);

            if(StringUtils.isNotEmpty(indexMappingsJson)){
                request.settings(indexSettingsJson,XContentType.JSON);
            }
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            if(createIndexResponse.isAcknowledged()){
                return R.fail(false,"创建索引成功");
            }
        } catch (IOException e) {
            log.error("调用es创建索引异常：{}",e);
            throw new RuntimeException("创建索引失败");
        }
        return R.fail(false,"创建索引失败");
    }

    @Override
    public R<Boolean> indexDelete(String indexName) {
        if (StringUtils.isEmpty(indexName)) {
            throw new ServiceException("indexName不能为空 ");
        }
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
//        request

        try {
            AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
            if (delete.isAcknowledged()) {
                return R.ok(true, "删除成功！");
            }
        } catch (IOException e) {
            log.error("删除索引失败：{}", e);
            throw new RuntimeException("调用es服务删除索引失败，详情请查看日志");
        }

        return R.fail(false, "删除索引失败");
    }

    @Override
    public R<Map> indexGetMapping(String indexName) {
        if (StringUtils.isEmpty(indexName)){
            throw new ServiceException("indexName不能为空");
        }
        GetMappingsRequest request = new GetMappingsRequest().indices(indexName);
        try {
            GetMappingsResponse response = restHighLevelClient.indices().getMapping(request, RequestOptions.DEFAULT);
            Map<String, MappingMetaData> mappings = response.mappings();
            MappingMetaData mappingMetaData = mappings.get(indexName);
            Map<String, Object> stringObjectMap = mappingMetaData.sourceAsMap();
            return R.ok(stringObjectMap,"操作成功");
        } catch (IOException e) {
            log.error("根据索引名称获取Mapping异常:{}",e);
            throw new RuntimeException("根据索引名称获取Mapping异常");
        }
    }

    @Override
    public Map<String, Object> getIndexDetails(String indexName) {
        if (StringUtils.isEmpty(indexName)){
            throw new ServiceException("indexName不能为空");
        }

        GetSettingsResponse response =null;
        try {
             response = restHighLevelClient.indices().getSettings(new GetSettingsRequest().indices(indexName),RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ImmutableOpenMap<String, Settings> indexToSettings = response.getIndexToSettings();
        Settings indexSettings = indexToSettings.get(indexName);


        GetMappingsResponse getMappingsResponse=null;
        try {
            getMappingsResponse = restHighLevelClient.indices().getMapping(new GetMappingsRequest().indices(indexName), RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        MappingMetaData mappingMetaData = getMappingsResponse.mappings().get(indexName);
        Map<String, Object> stringObjectMap = mappingMetaData.sourceAsMap();

        Map<String, String> settingsMap = new HashMap<>();
        for (String key : indexSettings.keySet()) {
            settingsMap.put(key, indexSettings.get(key));
        }

        Map<String, Object> result = new HashMap<>();
        result.put("settings", settingsMap);
        result.put("mappings", stringObjectMap);
        return result;
    }

    @Override
    public boolean addFieldToMapping(EsIndexVo esIndexVo) {

        try {
            PutMappingRequest request = new PutMappingRequest(esIndexVo.getIndexName());
            request.source(esIndexVo.getIndexSettings().toString(), XContentType.JSON);
            // 执行请求
            restHighLevelClient.indices().putMapping(request, RequestOptions.DEFAULT);
            return true;
        }  catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public R indexDel(EsDocDelVo esDocDelVo) {
        if(esDocDelVo==null){
            throw new ServiceException("esDocDelVo不能为空");
        }
        DeleteByQueryRequest request = new DeleteByQueryRequest(esDocDelVo.getIndexName());
        request.setQuery(QueryBuilders.matchQuery(esDocDelVo.getIndexName(),esDocDelVo.getIndexFileValue()));

        try {
            BulkByScrollResponse response = restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
            long deleted = response.getDeleted();
            if(deleted>0){
                return R.ok(true,"删除成功");
            }

        } catch (IOException e) {
            log.error("删除索引失败：{}", e);
            throw new RuntimeException(e);
        }
        return R.fail(false, "删除索引失败");
    }

    @Override
    public List<String> getAllIndex() {
        List<String> list = new ArrayList<>();
        GetIndexRequest request = new GetIndexRequest("_all"); // "_all" 表示所有索引
        GetIndexResponse getIndexResponse = null;
        try {
            getIndexResponse = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 从响应中提取索引名列表
        for (String index : getIndexResponse.getIndices()) {
            list.add(index);
        }
        return list;
    }




}


